package com.haiberg.framework.web.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;


/*
 * 不需要实现任何接口，也不需要继承任何的类
 */
@Controller
public class HelloWorldController {
	private static final Logger LOG = Logger.getLogger(HelloWorldController.class);
	/**
	 * 方法都可以接受的参数(参数数量和顺序没有限制)： HttpServletRequest,HttpServletResponse,HttpSession(session必须是可用的) ,PrintWriter,Map,Model,@PathVariable(任意多个)， @RequestParam（任意多个）， @CookieValue （任意多个），@RequestHeader，Object（pojo对象） ,BindingResult等等
	 * 
	 * 返回值可以是：String(视图名)，void（用于直接response），ModelAndView，Map ，Model，任意其它任意类型的对象（默认放入model中，名称即类型的首字母改成小写），视图名默认是请求路径
	 */
	@RequestMapping("/helloWorld")
	public ModelAndView helloWorld() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("login");
		mav.addObject("message", "Hello World!");
		return mav;
	}
	
	@RequestMapping("/fileUpload")
	public ModelAndView fileUpload() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("upload");
		mav.addObject("message", "Hello World!");
		return mav;
	}
	@RequestMapping("/upload")
	public ModelAndView handleRequest(HttpServletRequest request,   
            HttpServletResponse response) throws Exception {   
        // 转型为MultipartHttpRequest：   
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
        // 获得文件：   
        List<MultipartFile> files = multipartRequest.getFiles("upload_file");
        BufferedInputStream bis = null;
    	BufferedOutputStream bos = null;
    	StringBuffer nameBuffer = new StringBuffer("");
    	String name = "";
    	String path = "";
        if(files != null)
        {
        	
        	for(MultipartFile file : files)
        	{
                name = new String(file.getOriginalFilename().getBytes("gbk"), "utf-8");
                if(name.equals("") || file.getSize()==0)
                	continue;
                if(nameBuffer.length() > 0)
                	nameBuffer.append(",");
                nameBuffer.append(name);
                
        		String fileName = name.substring(
        				name.lastIndexOf('\\') + 1, name.length());
        		
        		File tempDir = new File(request.getRealPath("file"));
        		if(!tempDir.exists() || tempDir.isDirectory())
        		{
        			if(!tempDir.exists())
        				tempDir.mkdir();
        		}
        		
        		path = request.getRealPath("file")
        				+ File.separatorChar + fileName;
        		// 上传文件
        		File uploadedFile = new File(path);
        		bis = new BufferedInputStream(file.getInputStream());
        		bos = new BufferedOutputStream(new FileOutputStream(uploadedFile));
        		byte[] buffer = new byte[1024];
        		int readBytes = -1;
        		while((readBytes = bis.read(buffer))!=-1)
        		{
        			bos.write(buffer);
        		}
        		bis.close();
        		bos.close();
        	}
        }
        
		
		// 打印上传成功信息
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print("<font size='2'>上传的文件为：" + nameBuffer.toString() + "<br>");
		out.print("保存的地址为：" + path + "</font>");
		LOG.debug("upload file success!");
		return null;  
	}
}
